package com.vueblog.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vueblog.common.Result;
import com.vueblog.entity.MBlog;
import com.vueblog.service.IMBlogService;
import com.vueblog.shiro.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 
 * @since 2022-02-17
 */
@RestController
public class MBlogController {

    @Autowired
    private IMBlogService blogService;

    @GetMapping("/blogs")
    public Result blogs(@RequestParam(defaultValue = "1") Integer pageNo, @RequestParam(defaultValue = "10") Integer pageSize) {
        if(pageSize <= 0) {
            pageSize = 10;
        } else if(pageSize>100) {
            pageSize = 100;
        }
        Page<MBlog> page = new Page(pageNo, pageSize);
        IPage data = blogService.page(page, new QueryWrapper<MBlog>().eq("status", 0).orderByDesc("created"));
        return Result.success(data);
    }

    //@RequiresAuthentication
    @GetMapping("/blog/{id}")
    public Result blog(@PathVariable Long id) {
        /*if(ShiroUtil.getAccountInfo()==null) {
            return Result.fail("未登陆");
        }*/
        MBlog blog = blogService.getById(id);
        if(blog != null) {
            //if(0==blog.getStatus() && blog.getUserId().equals(ShiroUtil.getAccountInfo().getId())) {
            if(0==blog.getStatus()) {
                return Result.success(blog);
            }
        }
        return Result.success(null);
    }

    @RequiresAuthentication
    @PostMapping("/blog/save")
    public Result blogSave(@Validated @RequestBody MBlog blog) {
        MBlog tmp = null;
        if(blog.getId() != null) {
            if(blog.getId()<=0) {
                return Result.fail("无效的BlogId");
            }
            tmp = blogService.getById(blog.getId());
            if(tmp != null) {
                if(tmp.getStatus()==null || 0!=tmp.getStatus() || !tmp.getUserId().equals(ShiroUtil.getAccountInfo().getId())) {
                    return Result.fail("无权限编辑");
                }
            }
        }
        if(tmp==null) {
            tmp = new MBlog();
            tmp.setUserId(ShiroUtil.getAccountInfo().getId());
            tmp.setCreated(LocalDateTime.now());
            tmp.setStatus(0);
        }
        BeanUtil.copyProperties(blog, tmp, "id", "userId", "created", "status");
        blogService.saveOrUpdate(tmp);

        return Result.success(null);
    }

}
